<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          size="small"
          clearable
          placeholder="输入名称或者描述搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="query.createDate" class="date-item" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!-- 表单渲染 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="520px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" style="width: 380px" />
        </el-form-item>

        <el-form-item label="角色代码" prop="code">
          <el-input v-model="form.code" style="width: 380px" />
        </el-form-item>

        <el-form-item label="数据范围" prop="dataScope">
          <el-select
            v-model="form.dataScope"
            style="width: 140px"
            placeholder="请选择数据范围"
            @change="changeScope"
          >
            <el-option
              v-for="item in dateScopes"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.dataScope === 'CUSTOMIZE'"
          label="数据权限"
          prop="orgs"
        >
          <treeselect
            v-model="orgDatas"
            :load-options="loadOrgs"
            :options="orgs"
            :normalizer="normalizer"
            multiple
            style="width: 380px"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input
            v-model="form.description"
            style="width: 380px"
            rows="5"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="crud.submitCU"
        >确认</el-button>
      </div>
    </el-dialog>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col
        :xs="24"
        :sm="24"
        :md="16"
        :lg="16"
        :xl="17"
        style="margin-bottom: 10px"
      >
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
          </div>
          <el-table
            ref="table"
            v-loading="crud.loading"
            highlight-current-row
            style="width: 100%"
            :data="crud.data"
            @selection-change="crud.selectionChangeHandler"
            @current-change="handleCurrentChange"
          >
            <el-table-column
              :selectable="checkboxT"
              type="selection"
              width="55"
            />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="code" label="角色代码" />
            <el-table-column
              :show-overflow-tooltip="true"
              prop="description"
              label="描述"
            />
            <el-table-column
              :show-overflow-tooltip="true"
              width="135px"
              prop="createDate"
              label="创建日期"
            />
            <el-table-column
              v-if="checkPer(['admin', 'system:role,edit', 'system:role,del'])"
              label="操作"
              width="130px"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <udOperation :data="scope.row" :permission="permission" />
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </el-card>
      </el-col>
      <!-- 菜单授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip
              class="item"
              effect="dark"
              content="选择指定角色分配菜单"
              placement="top"
            >
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              v-permission="['admin', 'system:role,edit']"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="savePrivilege"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            lazy
            :data="menus"
            :default-checked-keys="menuIds"
            :load="getMenuDatas"
            :props="defaultProps"
            check-strictly
            accordion
            show-checkbox
            node-key="id"
            @check="menuChange"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudRoles from '@/api/system/role'
import { getOrgTree, findAll } from '@/api/system/org'
import { getTree, getChildIds } from '@/api/system/privilege'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import DateRangePicker from '@/components/DateRangePicker'

const defaultForm = {
  id: null,
  name: null,
  code: null,
  orgs: [],
  description: null,
  dataScope: '全部'
}
export default {
  name: 'Role',
  components: {
    Treeselect,
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    DateRangePicker
  },
  cruds() {
    return CRUD({
      title: '角色',
      url: 'api/sys/roles/page',
      sort: 'id,asc',
      crudMethod: { ...crudRoles }
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'title',
        isLeaf: 'leaf'
      },
      dateScopes: [
        { key: 'ALL', value: '全部' },
        { key: 'THIS_LEVEL', value: '本级' },
        { key: 'CUSTOMIZE', value: '自定义' }
      ],
      currentId: 0,
      menuLoading: false,
      showButton: false,
      menus: [],
      menuIds: [],
      orgs: [],
      orgDatas: [], // 多选时使用
      permission: {
        add: ['admin', 'system:role,create'],
        edit: ['admin', 'system:role,edit'],
        del: ['admin', 'system:role,del']
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入代码', trigger: 'blur' }],
        permission: [
          { required: true, message: '请输入权限', trigger: 'blur' }
        ]
      }
    }
  },
  created() {},
  methods: {
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    getMenuDatas(node, resolve) {
      setTimeout(() => {
        getTree(node.data.id ? { pid: node.data.id } : { pid: null }).then(
          (res) => {
            resolve(res)
          }
        )
      }, 100)
    },
    [CRUD.HOOK.afterRefresh]() {
      this.$refs.menu.setCheckedKeys([])
    },
    // 新增前初始化部门信息
    [CRUD.HOOK.beforeToAdd]() {
      this.orgDatas = []
    },
    // 编辑前初始化自定义数据权限的部门信息
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.orgDatas = []
      if (form.dataScope === 'CUSTOMIZE') {
        this.getSupOrg(form.orgs)
      }
      const _this = this
      form.orgs.forEach(function(org) {
        _this.orgDatas.push(org.id)
      })
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.dataScope === 'CUSTOMIZE' && this.orgDatas.length === 0) {
        this.$message({
          message: '自定义数据权限不能为空',
          type: 'warning'
        })
        return false
      } else if (crud.form.dataScope === 'CUSTOMIZE') {
        const orgs = []
        this.orgDatas.forEach(function(data) {
          const org = { id: data }
          orgs.push(org)
        })
        crud.form.orgs = orgs
      } else {
        crud.form.orgs = []
      }
      return true
    },
    // 触发单选
    handleCurrentChange(val) {
      if (val) {
        const _this = this
        // 清空菜单的选中
        this.$refs.menu.setCheckedKeys([])
        // 保存当前的角色id
        this.currentId = val.id
        // 初始化默认选中的key
        this.menuIds = []
        crudRoles.getRolePrivilege(this.currentId).then((res) => {
          this.menuIds = res
          console.info(this.menuIds)
          this.showButton = true
        })
      }
    },
    menuChange(menu) {
      // 获取该节点的所有子节点，id 包含自身
      getChildIds({ id: menu.id }).then((childIds) => {
        // 判断是否在 menuIds 中，如果存在则删除，否则添加
        if (this.menuIds.indexOf(menu.id) !== -1) {
          for (let i = 0; i < childIds.length; i++) {
            const index = this.menuIds.indexOf(childIds[i])
            if (index !== -1) {
              this.menuIds.splice(index, 1)
            }
          }
        } else {
          for (let i = 0; i < childIds.length; i++) {
            const index = this.menuIds.indexOf(childIds[i])
            if (index === -1) {
              this.menuIds.push(childIds[i])
            }
          }
        }

        this.$refs.menu.setCheckedKeys(this.menuIds)
      })
    },
    // 保存菜单
    savePrivilege() {
      this.menuLoading = true
      const role = { roleId: this.currentId, privilegeIds: this.menuIds }

      crudRoles.editPrivileges(role).then(() => {
        this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.menuLoading = false
      })
    },
    // 获取部门数据
    getOrgs() {
      getOrgTree({ enabled: true }).then((res) => {
        this.orgs = res.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupOrg(orgs) {
      const ids = []
      orgs.forEach((dept) => {
        ids.push(dept.id)
      })
      findAll(ids).then((res) => {
        const date = res
        this.buildDepts(date)
        this.orgs = date
      })
    },
    buildDepts(orgs) {
      orgs.forEach((data) => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据
    loadOrgs({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getOrgTree({ enabled: true, pid: parentNode.id }).then((res) => {
          parentNode.children = res.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 如果数据权限为自定义则获取部门数据
    changeScope() {
      if (this.form.dataScope === 'CUSTOMIZE') {
        this.getOrgs()
      }
    },
    checkboxT(row) {
      return true
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .vue-treeselect__multi-value {
  margin-bottom: 0;
}
::v-deep .vue-treeselect__multi-value-item {
  border: 0;
  padding: 0;
}
</style>
